package com.touka.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.touka.common.Result;
import com.touka.entity.User;
import com.touka.service.UserService;
import com.touka.utils.SMSUtils;
import com.touka.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
  @Autowired
  private UserService userService;

  @Autowired
  private RedisTemplate redisTemplate;

  /**
   * 发送手机短信验证码
   *
   * @param user
   * @return
   */
  @PostMapping("/sendMsg")
  public Result<String> sendMsg(@RequestBody User user, HttpSession session) {
    log.info("发送手机短信验证码：{}", user.getPhone());
    if (user.getPhone() != null) {
      // 生成随机验证码
      String code = ValidateCodeUtils.generateValidateCode(4).toString();
      log.info("code:{}", code);

      // 调用阿里云提供的短信服务API完成发送短信
      SMSUtils.sendMessage("瑞吉外卖", "", user.getPhone(), code);

      // 将需要生成的验证码保存到Session
      // session.setAttribute(user.getPhone(), code);

      // 将生成的验证码保存到Redis中，并设置有效期为5分钟
      redisTemplate.opsForValue().set(user.getPhone(), code, 5, TimeUnit.MINUTES);
      return Result.success(code);

    }
    return Result.error("短信发送失败");
  }

  /**
   * 移动端用户登录
   *
   * @param login
   * @param session
   * @return
   */
  @PostMapping("/login")
  public Result<User> login(@RequestBody Map<String, String> login, HttpSession session) {
    log.info("移动端用户登录：{}", login);

    String phone = login.get("phone");
    String code = login.get("code");

    // 从session取出验证码
    // String codeInSession = session.getAttribute(phone).toString();
    // 从Redis中取出保存的验证码
    String codeInRedis = (String) redisTemplate.opsForValue().get(phone);

    // 进行code比较
    if (codeInRedis != null && codeInRedis.equals(code)) {
      // 验证成功
      User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getPhone, phone));
      if (user == null) {
        // 该用户不存在，自动注册
        user = new User();
        user.setPhone(phone);
        user.setStatus(1);
        userService.save(user);
      }
      session.setAttribute("user", user.getId());

      // 如果用户登录成功，则删除Redis中缓存的验证码
      redisTemplate.delete(phone);
      
      return Result.success(user);
    }
    return Result.error("登录失败");
  }

  /**
   * 退出登录
   *
   * @param session
   * @return
   */
  @PostMapping("/loginout")
  public Result<String> logout(HttpSession session) {
    session.removeAttribute("user");
    return Result.success("退出登录成功");
  }
}
